package com.tansun.easycare.rule.rulegroup.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.tansun.easycare.rule.common.model.BaseBean;
import com.tansun.easycare.rule.common.model.RuleSetParamInfo;
import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.GroupFact;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.rulebasebean.RuleItem;
import com.tansun.easycare.rule.common.service.impl.RuleBaseServiceImpl;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.referencedata.entity.RuleReferenceData;
import com.tansun.easycare.rule.rulegroup.entity.RuleEntry;
import com.tansun.easycare.rule.rulegroup.entity.RuleGroup;
import com.tansun.easycare.rule.rulegroup.model.ComplexRuleGroup;
import com.tansun.easycare.rule.rulegroup.model.RuleEditEntity;
import com.tansun.easycare.rule.rulegroup.model.RuleEntryEntity;
import com.tansun.easycare.rule.rulegroup.model.RuleExpessVO;
import com.tansun.easycare.rule.rulegroup.model.RuleSetExpressVO;
import com.tansun.easycare.rule.rulegroup.service.RuleParseExpService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.utils.DroolsUtils;
import com.tansun.rule.model.toolbean.RuleModel.RuleType;

@Service
public class RuleParseExpServiceImpl implements RuleParseExpService {

	
	@Override
	public  List<RuleSetExpressVO> parseFactExpress(String factStr,RuleSetParamInfo newSetParamInfo,RuleSetParamInfo oldParamInfo,boolean setFlag){
		List<RuleSetExpressVO> ruleSet = JSON.parseArray(factStr, RuleSetExpressVO.class);
		for (RuleSetExpressVO ruleExpress :ruleSet) {
			if (ruleExpress.getConditions() !=null) {
				ruleExpress.getConditions().forEach(item ->{
					if (setFlag) {
						if (BaseBean.TYPE_BOM.equals(item.getType())) {
							if (oldParamInfo.getCode().equals(item.getName())) {
							  item.setName(newSetParamInfo.getCode());
							  item.setLabel(newSetParamInfo.getName());
							}
						}
					}else {
						if (BaseBean.OBJ_TYPE_FIELD.equals(item.getType())) {
							if (oldParamInfo.getCode().equals(item.getName())) {
							  item.setName(newSetParamInfo.getCode());
							   item.setLabel(newSetParamInfo.getName());
							}
						}
					}
				});
			}
			if (ruleExpress.getAction() != null) {
				ruleExpress.getAction().forEach(item ->{
					if (setFlag) {
						if (BaseBean.TYPE_BOM.equals(item.getType())) {
							if (oldParamInfo.getCode().equals(item.getName())) {
								item.setName(newSetParamInfo.getCode());
								item.setLabel(newSetParamInfo.getName());
							}
						}
					}else {
						if (BaseBean.OBJ_TYPE_FIELD.equals(item.getType())) {
							if (oldParamInfo.getCode().equals(item.getName())) {
								item.setName(newSetParamInfo.getCode());
								item.setLabel(newSetParamInfo.getName());
							}
						}
					}
				});
			}
		}
		return  ruleSet;
	}
	
	public String parseFact(String factStr, boolean isJavaFunc, RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
		List<RuleSetExpressVO> ruleSet = JSON.parseArray(factStr, RuleSetExpressVO.class);
		return parseFact(ruleSet,isJavaFunc,ruleDrlEvent);
	}
	
	public String parseFact(List<RuleSetExpressVO> ruleSet, boolean isJavaFunc, RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
		RuleSetExpressVO ruleSetExpressVO = null;

		StringBuffer strBuf = new StringBuffer();

		int  len = ruleSet.size();
		for (int i = 0; i < len; i++) {
			ruleSetExpressVO = ruleSet.get(i);
			strBuf.append(ruleSetExpressVO.getLeftOpt());
			List<RuleExpessVO> conditions = ruleSetExpressVO.getConditions();
			parseConditions(strBuf, isJavaFunc,conditions,ruleDrlEvent);
			if (ruleSetExpressVO.getLogicOpt() !=null) {
				String  oppL = ruleSetExpressVO.getLogicOpt().toLowerCase();
				if ( "and".equals(oppL) || "&&".equals(oppL)) {
					ruleSetExpressVO.setLogicOpt("&&");
				}else if ( "or".equals(oppL) || "||".equals(oppL)) {
					ruleSetExpressVO.setLogicOpt("||");
				}else {
					if (i<len-1)
					  ruleSetExpressVO.setLogicOpt("&&");	
				}
			}
			strBuf.append(ruleSetExpressVO.getRightOpt() + " " + ruleSetExpressVO.getLogicOpt() + "  \n");
		}
		return strBuf.toString();

	}
	
	public void parseConditions(StringBuffer strBuf,boolean isJavaFunc,List<RuleExpessVO> conditions,RuleBaseServiceImpl<?, ?> ruleDrlEvent) {
		RuleExpessVO ruleExpessVO = null;
		String datasetName = "";
		String fieldName = "";
		for (int j = 0; j < conditions.size(); j++) {
			ruleExpessVO = conditions.get(j);
			if (BaseBean.TYPE_BOM.equals(ruleExpessVO.getType())) {
				datasetName = ruleExpessVO.getName();
				j = j + 1;
				ruleExpessVO = conditions.get(j);
				if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType())) {
					fieldName = ruleExpessVO.getName();
					if("func".equals(datasetName)) {
						strBuf.append(" " + datasetName + "_"+ fieldName + "($insertMap,metaMap)");
					}else if(isJavaFunc) {
						strBuf.append(" " + ruleDrlEvent.genernalJavaStr(datasetName, fieldName, null, ruleExpessVO.getDataType()) + " ");
					}else {
						strBuf.append(" " + ruleDrlEvent.genernalWhenStr(datasetName, fieldName, "") + " ");
					}
				}
			} else if (BaseBean.TYPE_SYMBOL.equals(ruleExpessVO.getType()) && !ruleExpessVO.getName().equals(";")) {
				strBuf.append(ruleExpessVO.getDrlSymbol() + " ");
			} else if (BaseBean.OBJ_TYPE_VALUE.equals(ruleExpessVO.getType())) {
				if(ruleExpessVO.isReplace()) {
					int start = strBuf.lastIndexOf("#[replace]#");
					if ("String".equals(ruleExpessVO.getDataType()) || "Date".equals(ruleExpessVO.getDataType())) {
						strBuf.replace(start, start+"#[replace]#".length(), "\"" + ruleExpessVO.getValue() + "\"");
					} else {
						strBuf.replace(start, start+"#[replace]#".length(), ruleExpessVO.getValue());
					}
				}else {
					RuleExpessVO  tmpExpessVO = this.findPreField(conditions, j);
					if (BaseBean.OBJ_TYPE_FIELD.equals(tmpExpessVO.getType())) {
						if ("String".equals(tmpExpessVO.getDataType())) {
							RuleExpessVO  expessVO  =  conditions.get(j-1);
							if ("startswith".equals(expessVO.getName().toLowerCase()) ||
									"endswith".equals(expessVO.getName().toLowerCase())) {
								strBuf.append("(\"" + ruleExpessVO.getValue() + "\") ");
							}else 
							  strBuf.append("\"" + ruleExpessVO.getValue() + "\" ");
						} else {
							strBuf.append(ruleExpessVO.getValue() + " ");
						}
					} else {
						strBuf.append(ruleExpessVO.getValue() + " ");
					}	
				}
			} else if (BaseBean.OBJ_FUNC_OPT.equals(ruleExpessVO.getType()) && "(".equals(ruleExpessVO.getName())) {

			} else if (BaseBean.TYPE_JFUN.equals(ruleExpessVO.getType())) {
				strBuf.append(ruleExpessVO.getDrlName());
			} else if (";".equals(ruleExpessVO.getName())) {

			} else if (BaseBean.TYPE_LOGIC.equals(ruleExpessVO.getType())) {
				if ("and".equals(ruleExpessVO.getName()) ) {
					strBuf.append("&&");
				}else if ("or".equals(ruleExpessVO.getName())) {
					strBuf.append("||");
				}else {
					strBuf.append(ruleExpessVO.getName());
				}
			} else {
				strBuf.append(ruleExpessVO.getName());
			}
		}
	}
	
	private RuleExpessVO  findPreField(List<RuleExpessVO> list,int  i) {
		int j = i-1;
		RuleExpessVO  ruleExpess = list.get(j);
		if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpess.getType())) {
			return  ruleExpess;
		}else {
			return this.findPreField(list, j);
		}
		
	}
	
	public String parseAction(String actionStr, boolean isJavaFunc, RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
		List<RuleSetExpressVO> ruleSet = JSON.parseArray(actionStr, RuleSetExpressVO.class);
		return parseAction(ruleSet,isJavaFunc,ruleDrlEvent);
	}

	public String parseAction(List<RuleSetExpressVO> ruleSet, boolean isJavaFunc, RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
		RuleSetExpressVO ruleSetExpressVO = null;
		RuleExpessVO ruleExpessVO = null;
		StringBuffer strBuf = new StringBuffer();
		String datasetName = "";
		String fieldName = "";
		boolean isSetValue = false;
		for (int i = 0; i < ruleSet.size(); i++) {
			ruleSetExpressVO = ruleSet.get(i);
			StringBuffer lineBuf = new StringBuffer();
			List<RuleExpessVO>  action = ruleSetExpressVO.getAction();
			if(action == null) {
				continue;
			}
			if("if".equals(action.get(0).getSymtype())) {
				parseConditions(lineBuf, true,action,ruleDrlEvent);
				continue;
			}
			String setValueStr = "";
			String symtype = "";
			for (int j = 0; j < action.size(); j++) {
				ruleExpessVO = action.get(j);
				if (BaseBean.TYPE_BOM.equals(ruleExpessVO.getType()) && ruleExpessVO.getLabel().contains("item")) {
					// 针对集合 过滤情况
					datasetName = ruleExpessVO.getName();
					String label = ruleExpessVO.getLabel().replace("集合", "");
					j = j + 1;
					ruleExpessVO = action.get(j);
					if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType())) {
						fieldName = ruleExpessVO.getName();
						String type = ruleExpessVO.getDataType();
						if("List".equals(ruleExpessVO.getCollection())) {
							type = "List";
						}else if("BigDecimal".equals(type)) {
							type = "Double";
						}else if("BigInteger".equals(type)) {
							type = "Long";
						}
						lineBuf.append(" (("+type+")((Map)"+label+").get(\"" + fieldName +"\")) ");
					}
					
				}else if (BaseBean.TYPE_BOM.equals(ruleExpessVO.getType())) {
					datasetName = ruleExpessVO.getName();
					j = j + 1;
					ruleExpessVO = action.get(j);
					if (action.size() >= j + 1) {
						RuleExpessVO setValue = action.get(j + 1);
						fieldName = ruleExpessVO.getName();
						if ("::=".equals(setValue.getDrlSymbol())) {// 动作处理中，赋值操作
							j = j + 1;
							if(isJavaFunc) {
								String type = ruleExpessVO.getDataType();
								if("BigDecimal".equals(type)) {
									type = "Double";
								}else if("BigInteger".equals(type)) {
									type = "Long";
								}
								setValueStr = "("+type+")ruleHelper.setValue($insertMap,\"" + datasetName + "." + fieldName + "\",";
							}else {
								setValueStr = "	ruleHelper.setValue($insertMap,\"" + datasetName + "." + fieldName + "\",";
							}
							isSetValue = true;
							continue;
						}
					}
					//针对变量
					if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType())) {
						fieldName = ruleExpessVO.getName();
						if("func".equals(datasetName)) {
							lineBuf.append(" " + datasetName + "_"+ fieldName + "($insertMap,metaMap)");
						}else if(isJavaFunc) {
							lineBuf.append(" " + ruleDrlEvent.genernalJavaStr(datasetName, fieldName, null, ruleExpessVO.getDataType()) + " ");
						}else {
							String type = ruleExpessVO.getDataType();
							if("List".equals(ruleExpessVO.getCollection())) {
								type = "List";
							}else if("BigDecimal".equals(type)) {
								type = "Double";
							}else if("BigInteger".equals(type)) {
								type = "Long";
							}
							String paramStr = " ((" + type + ")"+ ruleDrlEvent.genernalWhenStr(datasetName, fieldName, "") + ") ";
							//如果前面有集合，j必须大于3
							if(j>3) {
								RuleExpessVO opt = action.get(j - 2);
								//集合的操作符位于j-2
								if(opt.isReplace()) {
									int start = lineBuf.lastIndexOf(".get(#[replace]#)");
									if(start != -1) {
										int index = lineBuf.lastIndexOf("((List)ruleHelper.getValue(");
										lineBuf.replace(index, index+"((List)ruleHelper.getValue(".length(), "("+ruleSetExpressVO.getAction().get(j-1).getDataType()+")(((List)ruleHelper.getValue(");
										lineBuf.append(")");
									}
									start = lineBuf.lastIndexOf("#[replace]#");
									lineBuf.replace(start, start+"#[replace]#".length(), paramStr);
								}else {
									lineBuf.append(paramStr);
								}
							}else {
								lineBuf.append(paramStr);
							}
						}
					}
				} else if (BaseBean.TYPE_SYMBOL.equals(ruleExpessVO.getType()) && !ruleExpessVO.getName().equals(";")) {
					if("for".equals(ruleExpessVO.getSymtype())&& j==0) {
						RuleExpessVO bom = action.get(1);
						RuleExpessVO field = action.get(2);
						long forNumber = ruleExpessVO.getForNumber();
						lineBuf.append("Object item"+forNumber+"= null;\n");
						lineBuf.append("List list"+forNumber+"= ((List)ruleHelper.getValue($insertMap,\""+bom.getName()+"."+field.getName()+"\"));\n");
						lineBuf.append("for(int idx"+forNumber+"=0;idx"+forNumber+"<list"+forNumber+".size();idx"+forNumber+"++){\n");
						lineBuf.append("	item"+forNumber+" = list"+forNumber+".get(idx"+forNumber+");\n");
						break;
					//集合过滤
					}else if("listFilter".equals(ruleExpessVO.getSymtype())&&".filter()".equals(ruleExpessVO.getName())) {
						String newLine = "List returnList = new ArrayList();\nfor(Object item:"+lineBuf.toString()+"){\n\tif(";
						lineBuf = new StringBuffer();
						lineBuf.append(newLine);
						symtype = "listFilter";
				    //集合映射
					}else if("listMap".equals(ruleExpessVO.getSymtype())&&".map()".equals(ruleExpessVO.getName())) {
						String newLine = "List returnList = new ArrayList();\nfor(Object item:"+lineBuf.toString()+"){\n\treturnList.add(";
						lineBuf = new StringBuffer();
						lineBuf.append(newLine);
						symtype = "listMap";
					}else if(".add(#[replace]#)".equals(ruleExpessVO.getDrlSymbol())) {
						RuleExpessVO bom = action.get(j-2);
						RuleExpessVO field = action.get(j-1);
						datasetName = bom.getName();
						fieldName = field.getName();
						lineBuf = new StringBuffer();
						lineBuf.append("ruleHelper.insertValue($insertMap,\""+datasetName+"."+fieldName+"\",#[replace]#)");
					}else {
						lineBuf.append(ruleExpessVO.getDrlSymbol() + " ");
					}
				}else if (BaseBean.OBJ_TYPE_VALUE.equals(ruleExpessVO.getType())) {
					if(ruleExpessVO.isReplace() && !"::=".equals(action.get(j - 1).getDrlSymbol())) {
						int start = lineBuf.lastIndexOf(".get(#[replace]#)");
						if(start != -1) {
							int index = lineBuf.lastIndexOf("((List)ruleHelper.getValue(");
							lineBuf.replace(index, index+"((List)ruleHelper.getValue(".length(), "("+ruleSetExpressVO.getAction().get(j-1).getDataType()+")(((List)ruleHelper.getValue(");
							lineBuf.append(")");
						}
						start = lineBuf.lastIndexOf("#[replace]#");
						if ("String".equals(ruleExpessVO.getDataType()) || "Date".equals(ruleExpessVO.getDataType())) {
							lineBuf.replace(start, start+"#[replace]#".length(), "\"" + ruleExpessVO.getValue() + "\"");
						} else {
							lineBuf.replace(start, start+"#[replace]#".length(), ruleExpessVO.getValue());
						}
					}else {
						RuleExpessVO tmpExpessVO = ruleSetExpressVO.getAction().get(j - 2);
						if (BaseBean.OBJ_TYPE_FIELD.equals(tmpExpessVO.getType())) {
							if ("String".equals(tmpExpessVO.getDataType()) || "Date".equals(tmpExpessVO.getDataType())) {
								lineBuf.append("\"" + ruleExpessVO.getValue() + "\" ");
							} else {
								lineBuf.append(ruleExpessVO.getValue() + " ");
							}
						} else {
							if(tmpExpessVO.isReplace() && ("String".equals(ruleExpessVO.getDataType()) || "Date".equals(ruleExpessVO.getDataType()))) {
								lineBuf.append("\"" + ruleExpessVO.getValue() + "\" ");
							}else {
								lineBuf.append(ruleExpessVO.getValue() + " ");
							}
						}
					}
				}else if(BaseBean.TYPE_JFUN.equals(ruleExpessVO.getType())){
					lineBuf.append(ruleExpessVO.getDrlName().replace("(", ""));
				}else if(BaseBean.OBJ_FUNC_OPT.equals(ruleExpessVO.getType())) {
					lineBuf.append(ruleExpessVO.getName());
				}else if(BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType()) && "for".equals(ruleExpessVO.getSymtype())) {
					lineBuf.append(ruleExpessVO.getName());
				} else if (BaseBean.TYPE_LOGIC.equals(ruleExpessVO.getType())) {
					if ("and".equals(ruleExpessVO.getName()) || "&&".equals(ruleExpessVO.getName())) {
						lineBuf.append("&&");
					}else if ("or".equals(ruleExpessVO.getName()) || "||".equals(ruleExpessVO.getName())) {
						lineBuf.append("||");
					}else {
						lineBuf.append(ruleExpessVO.getName());
					}
				}
			}
			if (isSetValue && ruleSetExpressVO.getAction().size() > 0 && StringUtils.isNotEmpty(setValueStr)) {
				String newLine = "";
				if("listFilter".equals(symtype) || "listMap".equals(symtype)) {
					newLine = lineBuf.toString().replace("returnList", "returnList"+i);
					newLine += "\n"+setValueStr.replace("ruleHelper.setValue", "ruleHelper.setValueList") + "returnList"+i+");\n";
				}else {
					newLine = setValueStr + lineBuf.toString() + ");\n";
				}
				lineBuf = new StringBuffer();
				lineBuf.append(newLine);
			}
			if(lineBuf.lastIndexOf("{")+2 == lineBuf.length()) {
				lineBuf.append("\n");
			}else if(lineBuf.lastIndexOf(";") == -1 && ruleSetExpressVO.getAction().size() > 0) {
				lineBuf.append(";\n");
			}
			strBuf.append(lineBuf.toString());
			isSetValue = true;
		}
		return strBuf.toString();
	}
	
	public void transformFactReference(String nodeContion, RuleManage ruleManage, Map<String, RuleReferenceData> map,Map<String,RuleDataparams> funcparamMap) {
		List<RuleSetExpressVO> ruleSet = JSON.parseArray(nodeContion, RuleSetExpressVO.class);
		transformFactReference(ruleSet, ruleManage, map, funcparamMap);
	}

	public void transformFactReference(List<RuleSetExpressVO> ruleSet, RuleManage ruleManage, Map<String, RuleReferenceData> map,Map<String,RuleDataparams> funcparamMap) {

		RuleSetExpressVO ruleSetExpressVO = null;
		RuleExpessVO ruleExpessVO = null;
		String datasetName = "";
		String fieldName = "";
		String dataType = "";
		String classNameCn = "";
		RuleReferenceData referData = null;
		for (int i = 0; i < ruleSet.size(); i++) {
			ruleSetExpressVO = ruleSet.get(i);
			List<RuleExpessVO> action = ruleSetExpressVO.getAction();
			if(action!=null) {
				for (int j = 0; j < action.size(); j++) {
					ruleExpessVO = action.get(j);
					if (BaseBean.TYPE_BOM.equals(ruleExpessVO.getType())) {
						datasetName = ruleExpessVO.getName();
						classNameCn = ruleExpessVO.getLabel();
						j = j + 1;
						ruleExpessVO = action.get(j);
						String contentType = "in";
						if (action.size() >= j + 1) {
							RuleExpessVO setValue = action.get(j + 1);
							fieldName = ruleExpessVO.getName();
							if ("::=".equals(setValue.getDrlSymbol()) || ".add(#[replace]#)".equals(setValue.getDrlSymbol())) {// 动作处理中，赋值操作  contentType为out
								j = j + 1;
								contentType = "out";
							}
						}
						if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType())) {
							fieldName = ruleExpessVO.getName();
							dataType = ruleExpessVO.getDataType();
							referData = new RuleReferenceData();
							referData.setClassName(datasetName);
							referData.setClassNamecn(classNameCn);
							referData.setNameen(fieldName);
							referData.setNamecn(ruleExpessVO.getLabel());
							referData.setDataType("func".equals(datasetName)?"func":dataType);
							referData.setId(null);
							referData.setManageId(ruleManage.getId());
							referData.setProjectCode(ruleManage.getProjectCode());
							referData.setCode(ruleManage.getCode());
							referData.setVersion(ruleManage.getVersion());
							referData.setContentType(contentType);
							referData.setModelType(ruleManage.getModelType());
							String key = datasetName + "|" + fieldName + "|"+contentType;
							map.put(key, referData);
							RuleDataparams ruleDataparams = new RuleDataparams();
							ruleDataparams.setClassName(datasetName);
							ruleDataparams.setName(fieldName);
							funcparamMap.put(key,ruleDataparams);
						}
					}
				}
			}
			if (ruleSetExpressVO.getConditions() != null) {
				for (int j = 0; j < ruleSetExpressVO.getConditions().size(); j++) {
					ruleExpessVO = ruleSetExpressVO.getConditions().get(j);
					if (BaseBean.TYPE_BOM.equals(ruleExpessVO.getType())) {
						datasetName = ruleExpessVO.getName();
						classNameCn = ruleExpessVO.getLabel();
						j = j + 1;
						ruleExpessVO = ruleSetExpressVO.getConditions().get(j);
						if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType())) {
							fieldName = ruleExpessVO.getName();
							dataType = ruleExpessVO.getDataType();
							referData = new RuleReferenceData();
							referData.setClassName(datasetName);
							referData.setClassNamecn(classNameCn);
							referData.setNameen(fieldName);
							referData.setNamecn(ruleExpessVO.getLabel());
							referData.setDataType("func".equals(datasetName)?"func":dataType);
							referData.setId(null);
							referData.setManageId(ruleManage.getId());
							referData.setProjectCode(ruleManage.getProjectCode());
							referData.setCode(ruleManage.getCode());
							referData.setVersion(ruleManage.getVersion());
							referData.setContentType("in");
							referData.setModelType(ruleManage.getModelType());
							String key = datasetName + "|" + fieldName + "|in";
							map.put(key, referData);
							RuleDataparams ruleDataparams = new RuleDataparams();
							ruleDataparams.setClassName(datasetName);
							ruleDataparams.setName(fieldName);
							funcparamMap.put(key,ruleDataparams);
						}
					}
				}
			}

		}

	}
	
	/**
     * 组织互斥条目的drl，互斥条目需要判断 
     * @param rc
     * @param generalEntrys
     * @param ruleManage
     * @throws Exception
     */
    public void organMutualExclusions(RuleCollection rc, List<RuleEntryEntity> mutualExclusions, RuleManage ruleManage,Set<String> initList, boolean isJavaFunc,Map<String, RuleReferenceData> refMap,Map<String,RuleDataparams> funcparamMap,boolean changeType,RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
    	String code = ruleManage.getCode();
    	List<String> entryNames = new ArrayList<String>();
        for(RuleEntryEntity entryEntity:mutualExclusions) {
        	// 条目信息
        	RuleEntry ruleEntry = entryEntity.getRuleEntry();
        	// 规则信息
         	List<RuleEditEntity> rules = entryEntity.getRules();
         	if(rules == null || rules.isEmpty())continue;
        	String entryCode = ruleEntry.getEntryCode();
        	String entryName = ruleEntry.getEntryName();
        	String accessMode = ruleEntry.getAccessMode();
        	// 条目条件
        	List<Fact> entryList = getEntryCondition(entryEntity, ruleManage, refMap, funcparamMap, isJavaFunc, ruleDrlEvent);

    		//判断条目名是否包含在列表中
			GroupFact groupfact = new GroupFact();
			groupfact.setContent("ruleHelper.valueNotInList($insertMap, \""+code+".activeEntryList\",\""+StringUtils.join(entryNames,"\",\"")+"\")");
    		
    		List<String> reasoncode = new ArrayList<String>();
    		List<String> tracks = new ArrayList<String>();
    		RuleItem ruleItem = null;
            for (RuleEditEntity editEntity: rules) {
            	// 规则的manage
            	RuleManage ruleRM = editEntity.getRuleManage();
            	// 规则列表
            	List<RuleGroup> list = editEntity.getRuleGroups();
            	for (RuleGroup ruleVo : list) {
	            	List<String> logsArr = new ArrayList<String>();//日志参数收集
	                logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\",\""+ruleVo.getRuleName()+"\",\""+ruleVo.getRuleScore()+"\",\""+ruleVo.getReasonCode()+"\");");
	                logsArr.add("droolsRuleLog.addTracks(\""+entryName+"_"+ruleVo.getRuleName()+"\");");
	                tracks.add(entryName+"]["+ruleVo.getRuleName());
	                // 创建RuleItem 
	        		ruleItem = new RuleItem();
	        		//规则名称
	                ruleItem.setRuleName(entryCode+"_"+ruleVo.getRuleName());
	                //日志内容
	                ruleItem.getdThen().setLogsArr(logsArr);
	                //条件
	                List<Fact> evals = ruleItem.getdWhen().getEvalList();
	                //动作
	                List<Action> actionList = ruleItem.getdThen().getListAction();
	                // 解析规则
	        		String evalstr = "";
	        		//解析规则条件及收集引用变量
	        		if(!StringUtils.isEmpty(ruleVo.getEvals())) {
	        			evalstr = parseFact(ruleVo.getEvals(),isJavaFunc, ruleDrlEvent);
	        			if(evalstr.endsWith("\n"))evalstr = evalstr.substring(0, evalstr.length()-2);
	    	    		//收集引用变量
	    	    		transformFactReference(ruleVo.getEvals(), ruleManage, refMap, funcparamMap);
	                	GroupFact gf = new GroupFact();
	                	gf.setContent(evalstr);
	                	evals.add(gf);
	        		}
	        		//解析规则动作及收集引用变量
	        		if(!StringUtils.isEmpty(ruleVo.getActions())) {
	            		String actionStr = parseAction(ruleVo.getActions(), isJavaFunc,ruleDrlEvent);
	            		//收集引用变量
	            		transformFactReference(ruleVo.getActions(), ruleManage, refMap, funcparamMap);
	            		actionList.add(new Action(actionStr));
	        		}
	                
	        		//解析else  
	        		//如果条件存在， 那else中的条件与规则的条件相反来判断else操作  如果evalstr不存在条件， 则默认未必命中规则， else不解析
	        		boolean needElse = !StringUtils.isEmpty(ruleVo.getActions()) && !StringUtils.isEmpty(evalstr);
	        		RuleItem ruleItemElse = new RuleItem();
	        		//条件
	                List<Fact> evalsElse = ruleItemElse.getdWhen().getEvalList();
	                //动作
	                List<Action> actionElseList = ruleItemElse.getdThen().getListAction();
	        		if(needElse) {
		        		//规则名称
	        			ruleItemElse.setRuleName(entryCode+"_"+ruleVo.getRuleName()+"_else");
		                //日志内容
	        			ruleItemElse.getdThen().setLogsArr(logsArr);
	                	GroupFact gf = new GroupFact();
	                	gf.setContent("("+evalstr+")==false");
	                	evalsElse.add(gf);
	    	    		String elseStr = parseAction(ruleVo.getElseActions(), isJavaFunc, ruleDrlEvent);
	    	    		if(elseStr.endsWith("\n"))elseStr = elseStr.substring(0, elseStr.length()-2);
	    	    		transformFactReference(ruleVo.getElseActions(), ruleManage, refMap, funcparamMap);//收集引用变量
	    	    		actionElseList.add(new Action(elseStr));
	        		}
	        		
	                String reasonList = "ruleHelper.insertValue($insertMap,\""+code+".reasonList\",\""+ruleVo.getReasonCode()+"\");";
	                actionList.add(new Action(reasonList));
	                String ruleScoreSum = "ruleHelper.deAccumulating($insertMap,\""+code+".ruleScoreSum\",\""+code+".activeList\",\""+ruleVo.getRuleName()+"\","+ruleVo.getRuleScore()+");";
	                actionList.add(new Action(ruleScoreSum));
	                String activeList = "ruleHelper.insertValue($insertMap,\""+code+".activeList\",\""+ruleVo.getRuleName()+"\");";
	                actionList.add(new Action(activeList));
	        		if(needElse) {
	        			actionElseList.add(new Action(reasonList));
	        			actionElseList.add(new Action(ruleScoreSum));
	        			actionElseList.add(new Action(activeList));
	        		}
	        		
	                if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {//优先级准入
	                	//优先级判断条件
	                	for(int i=0;i<entryList.size();i++) {
	                    	Fact fact = entryList.get(i);
	                    	evals.add(i, fact);
	                    	if(needElse) {
	                    		evalsElse.add(i, fact);
	                    	}
	                    }
	                	String priorityVar = (changeType?"(Long)":"")+"ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\")";
	                	GroupFact gf = new GroupFact();
	                	gf.setContent(priorityVar+" == "+ruleVo.getPriority()+" || "+priorityVar+" == 99999");
	                	evals.add(0,gf);
	                	
	            		//优先级动作
	            		String priorityCode = "ruleHelper.setValueNotMatch($insertMap, \""+code+"."+entryCode+"_priority\","+ruleVo.getPriority()+");";
		                actionList.add(new Action(priorityCode));
		                
                    	if(needElse) {
                    		evalsElse.add(0, gf);
                    		actionElseList.add(new Action(priorityCode));
                    	}
	                }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
	                	//添加条件准入条件，插入首位置
	                	for(int i=0;i<entryList.size();i++) {
	                    	Fact fact = entryList.get(i);
	                    	evals.add(i, fact);
	                    	if(needElse) {
	                    		evalsElse.add(i, fact);
	                    	}
	                    }
	                }else if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
	                	reasoncode.add(ruleVo.getReasonCode());
	                	//权重累加动作
	                    String totalweight = "ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\","+ruleVo.getRuleweight()+"+"+(changeType?"(Double)":"")+"ruleHelper.getValue($insertMap,\""+code+"."+entryCode+"_totalweight\"));";
	                    actionList.add(new Action(totalweight));
                    	if(needElse) {
                    		actionElseList.add(new Action(totalweight));
                    	}
	                }
	            	//添加判断，判断条目名是否包含在列表中
	        		if(entryNames.size()>0) {
	        			evals.add(0, groupfact);
	            	}
	                rc.getListItem().add(ruleItem);
            	}
            }
            
        	List<String> logsArr = new ArrayList<String>();//日志参数收集
            logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\");");
            logsArr.add("droolsRuleLog.addTracks(\""+entryName+"\");");
            
            RuleItem ruleItemOther = new RuleItem();
            ruleItemOther.setAddlog(0);
        	ruleItemOther.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid()+entryName);
        	if(ruleItem!=null) {
        		ruleItemOther.setSalience(ruleItem.getSalience());
        	}else {
        		ruleItemOther.setSalience(0);
        	}
            if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
            	//权重初始化
            	initList.add("ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\",0.0);");
            	
            	if(entryList.size()>0) {//没有命中
	            	GroupFact fact = new GroupFact();
	            	fact.setContent("!( "+entryList.get(0).getContent()+" )");
	            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	}
            	String removeReasonList = "ruleHelper.removeListValue($insertMap,\""+code+".reasonList\",\""+StringUtils.join(reasoncode,"\",\"")+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(removeReasonList));
            	String removeTrack = "droolsRuleLog.removeTracks(\""+StringUtils.join(tracks,"\",\"")+"\");";//删除命中轨迹
            	ruleItemOther.getdThen().getListAction().add(new Action(removeTrack));
            	
            	//判断是否添加条目
            	RuleItem ruleItemOther2 = new RuleItem();
            	ruleItemOther2.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
            	ruleItemOther2.setSalience(ruleItemOther.getSalience());
            	ruleItemOther2.getdWhen().setEvalList(entryList); 
            	ruleItemOther2.getdThen().setLogsArr(ruleItemOther.getdThen().getLogsArr());
            	if(entryNames.size()>0) {
        			ruleItemOther2.getdWhen().getEvalList().add(0, groupfact);
            	}
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther2.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther2.getdThen().setLogsArr(logsArr);
            	ruleItemOther2.setAddlog(0);
            	rc.getListItem().add(ruleItemOther2);
            }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
            	ruleItemOther.getdWhen().setEvalList(entryList);
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }else if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {
            	//优先级初始化
            	initList.add("ruleHelper.setValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\",99999);");
            	
            	GroupFact fact = new GroupFact();
            	fact.setContent((changeType?"(Long)":"")+"ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\") != 99999");
            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }
        	//添加判断，判断条目名是否包含在列表中
    		if(entryNames.size()>0) {
    			ruleItemOther.getdWhen().getEvalList().add(0, groupfact);
        	}
            rc.getListItem().add(ruleItemOther);
            entryNames.add(entryName);
        }
    }
    
    /**
     * 组织普通条目的drl
     * @param rc
     * @param generalEntrys
     * @param ruleManage
     * @throws Exception
     */
    public void organGeneralEntrys(RuleCollection rc, List<RuleEntryEntity> generalEntrys, RuleManage ruleManage,Set<String> initList, boolean isJavaFunc,Map<String, RuleReferenceData> refMap,Map<String,RuleDataparams> funcparamMap,boolean changeType,RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
    	String code = ruleManage.getCode();
        for(RuleEntryEntity entryEntity:generalEntrys) {
        	// 条目信息
        	RuleEntry ruleEntry = entryEntity.getRuleEntry();
        	// 规则信息
         	List<RuleEditEntity> rules = entryEntity.getRules();
         	if(rules == null || rules.isEmpty())continue;
        	String entryCode = ruleEntry.getEntryCode();
        	String entryName = ruleEntry.getEntryName();
        	String accessMode = ruleEntry.getAccessMode();
        	// 条目条件
        	List<Fact> entryList = getEntryCondition(entryEntity, ruleManage, refMap, funcparamMap, isJavaFunc, ruleDrlEvent);
        	
    		List<String> reasoncode = new ArrayList<String>();
    		List<String> tracks = new ArrayList<String>();
    		RuleItem ruleItem = null;
            for (RuleEditEntity editEntity: rules) {
            	// 规则的manage
            	RuleManage ruleRM = editEntity.getRuleManage();
            	// 规则列表
            	List<RuleGroup> list = editEntity.getRuleGroups();
            	for (RuleGroup ruleVo : list) {
	            	List<String> logsArr = new ArrayList<String>();//日志参数收集
	                logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\",\""+ruleVo.getRuleName()+"\",\""+ruleVo.getRuleScore()+"\",\""+ruleVo.getReasonCode()+"\");");
	                logsArr.add("droolsRuleLog.addTracks(\""+entryName+"]["+ruleVo.getRuleName()+"\");");
	                tracks.add(entryName+"]["+ruleVo.getRuleName());
	                // 创建RuleItem 
	        		ruleItem = new RuleItem();
	        		//规则名称
	                ruleItem.setRuleName(entryCode+"_"+ruleVo.getRuleName());
	                //日志内容
	                ruleItem.getdThen().setLogsArr(logsArr);
	                //条件
	                List<Fact> evals = ruleItem.getdWhen().getEvalList();
	                //动作
	                List<Action> actionList = ruleItem.getdThen().getListAction();
	                // 解析规则
	        		String evalstr = "";
	        		//解析规则条件及收集引用变量
	        		if(!StringUtils.isEmpty(ruleVo.getEvals())) {
	        			evalstr = parseFact(ruleVo.getEvals(), isJavaFunc, ruleDrlEvent);
	        			if(evalstr.endsWith("\n"))evalstr = evalstr.substring(0, evalstr.length()-2);
	    	    		//收集引用变量
	    	    		transformFactReference(ruleVo.getEvals(), ruleManage, refMap, funcparamMap);
	                	GroupFact gf = new GroupFact();
	                	gf.setContent(evalstr);
	                	evals.add(gf);
	        		}
	        		//解析规则动作及收集引用变量
	        		if(!StringUtils.isEmpty(ruleVo.getActions())) {
	            		String actionStr = parseAction(ruleVo.getActions(), isJavaFunc, ruleDrlEvent);
	            		//收集引用变量
	            		transformFactReference(ruleVo.getActions(), ruleManage, refMap, funcparamMap);
	            		actionList.add(new Action(actionStr));
	        		}
	                
	        		//解析else  
	        		//如果条件存在， 那else中的条件与规则的条件相反来判断else操作  如果evalstr不存在条件， 则默认未必命中规则， else不解析
	        		boolean needElse = !StringUtils.isEmpty(ruleVo.getActions()) && !StringUtils.isEmpty(evalstr);
	        		RuleItem ruleItemElse = new RuleItem();
	        		//条件
	                List<Fact> evalsElse = ruleItemElse.getdWhen().getEvalList();
	                //动作
	                List<Action> actionElseList = ruleItemElse.getdThen().getListAction();
	        		if(needElse) {
		        		//规则名称
	        			ruleItemElse.setRuleName(entryCode+"_"+ruleVo.getRuleName()+"_else");
		                //日志内容
	        			ruleItemElse.getdThen().setLogsArr(logsArr);
	                	GroupFact gf = new GroupFact();
	                	gf.setContent("("+evalstr+")==false");
	                	evalsElse.add(gf);
	    	    		String elseStr = parseAction(ruleVo.getElseActions(), isJavaFunc,ruleDrlEvent);
	    	    		if(elseStr.endsWith("\n"))elseStr = elseStr.substring(0, elseStr.length()-2);
	    	    		transformFactReference(ruleVo.getElseActions(), ruleManage, refMap, funcparamMap);//收集引用变量
	    	    		actionElseList.add(new Action(elseStr));
	        		}
	        		
	                // 额外添加到动作的内容
	                String reasonList = "ruleHelper.insertValue($insertMap,\""+code+".reasonList\",\""+ruleVo.getReasonCode()+"\");";
	                actionList.add(new Action(reasonList));
	                String ruleScoreSum = "ruleHelper.deAccumulating($insertMap,\""+code+".ruleScoreSum\",\""+code+".activeList\",\""+ruleVo.getRuleName()+"\","+ruleVo.getRuleScore()+");";
	                actionList.add(new Action(ruleScoreSum));
	                String activeList = "ruleHelper.insertValue($insertMap,\""+code+".activeList\",\""+ruleVo.getRuleName()+"\");";
	                actionList.add(new Action(activeList));
	        		if(needElse) {
	        			actionElseList.add(new Action(reasonList));
	        			actionElseList.add(new Action(ruleScoreSum));
	        			actionElseList.add(new Action(activeList));
	        		}
	                if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {//优先级准入
	                	//优先级判断条件
	                	for(int i=0;i<entryList.size();i++) {
	                    	Fact fact = entryList.get(i);
	                    	evals.add(i, fact);
	                    	if(needElse) {
	                    		evalsElse.add(i, fact);
	                    	}
	                    }
	                	String priorityVar = (changeType?"(Long)":"")+"ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\")";
	                	GroupFact gf = new GroupFact();
	                	gf.setContent(priorityVar+" == "+ruleVo.getPriority()+" || "+priorityVar+" == 99999");
	                	evals.add(0,gf);
	            		//优先级动作
	            		String priorityCode = "ruleHelper.setValueNotMatch($insertMap, \""+code+"."+entryCode+"_priority\","+ruleVo.getPriority()+");";
		                actionList.add(new Action(priorityCode));
		                
                    	if(needElse) {
                    		evalsElse.add(0, gf);
                    		actionElseList.add(new Action(priorityCode));
                    	}
	                }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
	                	//添加条件准入条件，插入首位置
	                	for(int i=0;i<entryList.size();i++) {
	                    	Fact fact = entryList.get(i);
	                    	evals.add(i, fact);
	                    	if(needElse) {
	                    		evalsElse.add(i, fact);
	                    	}
	                    }
	                }else if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
	                	reasoncode.add(ruleVo.getReasonCode());
	                	//权重累加动作
	                    String totalweight = "ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\","+ruleVo.getRuleweight()+"+"+(changeType?"(Double)":"")+"ruleHelper.getValue($insertMap,\""+code+"."+entryCode+"_totalweight\"));";
	                    actionList.add(new Action(totalweight));
                    	if(needElse) {
                    		actionElseList.add(new Action(totalweight));
                    	}
	                }
	                rc.getListItem().add(ruleItem);
                	if(needElse) {
                		rc.getListItem().add(ruleItemElse);
                	}
            	}
            }
            
        	List<String> logsArr = new ArrayList<String>();//日志参数收集
            logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\");");
            logsArr.add("droolsRuleLog.addTracks(\""+entryName+"\");");
            
            RuleItem ruleItemOther = new RuleItem();
            ruleItemOther.setAddlog(0);
        	ruleItemOther.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
        	if(ruleItem!=null) {
        		ruleItemOther.setSalience(ruleItem.getSalience());
        	}else {
        		ruleItemOther.setSalience(0);
        	}
            if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
            	//权重初始化
            	initList.add("ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\",0.0);");
            	
            	if(entryList.size()>0) {//权重不符条件，删除原因代码
	            	GroupFact fact = new GroupFact();
	            	fact.setContent("!( "+entryList.get(0).getContent()+" )");
	            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	}
            	String removeReasonList = "ruleHelper.removeListValue($insertMap,\""+code+".reasonList\",\""+StringUtils.join(reasoncode,"\",\"")+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(removeReasonList));
            	String removeTrack = "droolsRuleLog.removeTracks(\""+StringUtils.join(tracks,"\",\"")+"\");";//删除命中轨迹
            	ruleItemOther.getdThen().getListAction().add(new Action(removeTrack));
            	
            	//判断是否添加条目，符合条件，添加
            	RuleItem ruleItemOther2 = new RuleItem();
            	ruleItemOther2.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
            	ruleItemOther2.setSalience(ruleItemOther.getSalience());
            	ruleItemOther2.getdWhen().setEvalList(entryList);
            	
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther2.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther2.getdThen().setLogsArr(logsArr);
            	ruleItemOther2.setAddlog(0);
            	rc.getListItem().add(ruleItemOther2);
            }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//
            	ruleItemOther.getdWhen().setEvalList(entryList);//规则命中
            	
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }else if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {//规则命中
            	//优先级初始化
            	initList.add("ruleHelper.setValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\",99999);");
            	
            	GroupFact fact = new GroupFact();
            	if(changeType) {
            		fact.setContent("(Long)ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\") != 99999");
            	}else {
            		fact.setContent("ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\") != 99999");
            	}
            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }
            rc.getListItem().add(ruleItemOther);
        }
    }
    
    /**
     * 将规则条目解析对应的条件
     * @param ruleEntryVO
     * @return
     * @throws Exception 
     */
    public List<Fact> getEntryCondition(RuleEntryEntity entryEntity, RuleManage ruleManage,Map<String, RuleReferenceData> refMap, Map<String,RuleDataparams> funcparamMap,boolean isJavaFunc,RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
    	//条件结果
    	List<Fact> facts = new ArrayList<Fact>();
    	// 条目信息
    	RuleEntry ruleEntry = entryEntity.getRuleEntry();
    	String accessMode = ruleEntry.getAccessMode();
    	if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode) || RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//条件准入 权重准入
    		String condition = ruleEntry.getConditions();
    		// 避免条件为[]时候，drl文件多出个()的准入条件导致执行错误
			JSONArray condictionArray = JSONArray.parseArray(condition);
			if(condictionArray!=null && condictionArray.size()>0) {
    	    	String evals = parseFact(ruleEntry.getConditions(), isJavaFunc,ruleDrlEvent);
    	    	//收集引用变量
    	    	transformFactReference(ruleEntry.getConditions(), ruleManage, refMap, funcparamMap);
        		GroupFact groupfact = new GroupFact();
        		groupfact.setContent(evals);
        		facts.add(groupfact);
    		}
    	}
    	for(Fact fact:facts) {
    		fact.setType(Fact.TYPE_ENTRY);
    	}
		return facts;
    	
    }
    
    
    /**
     * 规则集保存，主要是drl版本生成
     * @param ruleEditEntity
     * @throws Exception
     */
    public String parseRuleGroupList(ComplexRuleGroup complexRuleGroup,Map<String, RuleReferenceData> refMap,Map<String,RuleDataparams> funcparamMap,boolean isJavaFunc,RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {

    	Set<String> initList =new HashSet<String>();
    	RuleManage ruleManage = complexRuleGroup.getRuleManage();
    	String code = ruleManage.getCode();
        RuleCollection rc = new RuleCollection();
        rc.setContentType(RuleType.policyrulegroup.toString());
        rc.setDrlName(ruleManage.getCode());
        rc.setVersion(ruleManage.getVersion());
        rc.setObjName(ruleManage.getName());
        initList.add("ruleHelper.setValue($insertMap,\""+code+".ruleScoreSum\",0.0);");
        List<RuleEntryEntity> generalEntrys= complexRuleGroup.getGeneralEntrys();
        if(generalEntrys!=null && !generalEntrys.isEmpty()) {
        	organGeneralEntrys(rc, generalEntrys, ruleManage, initList, isJavaFunc,refMap, funcparamMap,false,ruleDrlEvent);
        }
        List<RuleEntryEntity> mutualExclusions= complexRuleGroup.getMutualExclusions();
        if(mutualExclusions!=null && !mutualExclusions.isEmpty()) {
        	organMutualExclusions(rc, mutualExclusions, ruleManage, initList, isJavaFunc,refMap, funcparamMap,false,ruleDrlEvent);
        }
        
        RuleItem ruleItem = new RuleItem();
        ruleItem.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
        ruleItem.setSalience(-999999);
        ruleItem.setAddlog(0);
        List<Action> actionList = ruleItem.getdThen().getListAction();
        String activegroupList = "ruleHelper.insertValue($insertMap,\"builtinParam.activegroupList\",\""+ruleManage.getName()+"\");";
        actionList.add(new Action(activegroupList));
        String setList = "ruleHelper.dRemoval($insertMap,\""+code+".activeList\");";
        actionList.add(new Action(setList));
        setList = "ruleHelper.dRemoval($insertMap,\""+code+".reasonList\");";
        actionList.add(new Action(setList));
        rc.getListItem().add(ruleItem);
        
        if(isJavaFunc) {
        	return DroolsUtils.convert2DrlFunc(rc,initList,RuleCollection.POLIRULEGRP,null);
        }else {
        	return DroolsUtils.convert2DrlTxt(rc,initList);
        }
        
    }

    public String parseFact2(String factStr, boolean isJavaFunc, RuleBaseServiceImpl<?, ?> ruleDrlEvent) throws Exception {
		List<RuleSetExpressVO> ruleSet = JSON.parseArray(factStr, RuleSetExpressVO.class);
		RuleSetExpressVO ruleSetExpressVO = null;
		RuleExpessVO ruleExpessVO = null;
		StringBuffer strBuf = new StringBuffer();
		String datasetName = "";
		String fieldName = "";
		int  len = ruleSet.size();
		// 循环每一行数据
		for (int i = 0; i < len; i++) {
			ruleSetExpressVO = ruleSet.get(i);
			strBuf.append(ruleSetExpressVO.getLeftOpt());
			// 对于一行的条件 以逻辑符号分割
			
			for (int j = 0; j < ruleSetExpressVO.getConditions().size(); j++) {
				ruleExpessVO = ruleSetExpressVO.getConditions().get(j);
				if (BaseBean.TYPE_BOM.equals(ruleExpessVO.getType())) {
					datasetName = ruleExpessVO.getName();
					j = j + 1;
					ruleExpessVO = ruleSetExpressVO.getConditions().get(j);
					if (BaseBean.OBJ_TYPE_FIELD.equals(ruleExpessVO.getType())) {
						fieldName = ruleExpessVO.getName();
						if(isJavaFunc) {
							strBuf.append(" " + ruleDrlEvent.genernalJavaStr(datasetName, fieldName, null, ruleExpessVO.getDataType()) + " ");
						}else {
							strBuf.append(" " + ruleDrlEvent.genernalWhenStr(datasetName, fieldName, "") + " ");
						}
					}
				} else if (BaseBean.TYPE_SYMBOL.equals(ruleExpessVO.getType()) && !ruleExpessVO.getName().equals(";")) {
					strBuf.append(ruleExpessVO.getDrlSymbol() + " ");
				} else if (BaseBean.OBJ_TYPE_VALUE.equals(ruleExpessVO.getType())) {
					RuleExpessVO  tmpExpessVO = this.findPreField(ruleSetExpressVO.getConditions(), j);
					if (BaseBean.OBJ_TYPE_FIELD.equals(tmpExpessVO.getType())) {
						if ("String".equals(tmpExpessVO.getDataType())) {
							strBuf.append("\"" + ruleExpessVO.getValue() + "\" ");
						} else {
							strBuf.append(ruleExpessVO.getValue() + " ");
						}
					} else
						strBuf.append(ruleExpessVO.getValue() + " ");
				} else if (BaseBean.OBJ_FUNC_OPT.equals(ruleExpessVO.getType()) && ruleExpessVO.getName().equals("(")) {

				} else if (BaseBean.TYPE_JFUN.equals(ruleExpessVO.getType())) {
					strBuf.append(ruleExpessVO.getDrlName());
				} else if (ruleExpessVO.getName().equals(";")) {

				} else if (BaseBean.TYPE_LOGIC.equals(ruleExpessVO.getType())) {
					String  oppL = ruleSetExpressVO.getLogicOpt().toLowerCase();
					if ("and".equals(ruleExpessVO.getName()) ) {
						strBuf.append("&&");
					}else if ("or".equals(ruleExpessVO.getName())) {
						strBuf.append("||");
					}else {
						strBuf.append(ruleExpessVO.getName());
					}
				} else {
					strBuf.append(ruleExpessVO.getName());
				}
			}
			if (ruleSetExpressVO.getLogicOpt() !=null) {
				String  oppL = ruleSetExpressVO.getLogicOpt().toLowerCase();
				if ("and".equals(oppL) ) {
					ruleSetExpressVO.setLogicOpt("&&");
				}else if ("or".equals(oppL)) {
					ruleSetExpressVO.setLogicOpt("||");
				}else {
					if (i<len-1)
					  ruleSetExpressVO.setLogicOpt("&&");	
				}
			}
			strBuf.append(ruleSetExpressVO.getRightOpt() + " " + ruleSetExpressVO.getLogicOpt() + "  \n");
		}
		return strBuf.toString();

	}

    
	private RuleReferenceData initReferenceData() {
		return null;
	}
 
}
